#include <QApplication>
#include <QQmlApplicationEngine>
#include <QResource>
#include <QtQml>
#include <QFile>

#include <TC/sources/Qml/TypeRegister.h>
#include <TC/sources/Qml/Engine.h>

#include <Request/NewsGroupManager.h>
#include <Request/NewsManager.h>
#include <MyQmlNetworkAccessManagerFactory.h>

void registerAllManagerType()
{
	using namespace TC::Request;
	qmlRegisterType<NewsGroupManager>("Cpp.Request", 1, 0, "NewsGroupManager");
	qmlRegisterType<NewsManager>("Cpp.Request", 1, 0, "NewsManager");
}

void loadTranslateFile(QGuiApplication &app, const QString &path)
{
	QTranslator *translator = new QTranslator;
	if (translator->load(path, ":/"))
	{
		qDebug() << "Translator loaded : " << path << endl;
		if (app.installTranslator(translator))
		{
			return;
		}
	}
	qWarning() << "Failed to load translator : " << path << endl;
}

int main(int argc, char *argv[])
{
	QApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
	QApplication app(argc, argv);

	// translator
	loadTranslateFile(app, "tc_zh");
	
	// cpp types -> qml types
	TC::Qml::registerAll();
	registerAllManagerType();
	
	// import path
	auto engine = TC::Qml::Engine::instance();
#ifdef _TCDEBUG
	engine->addImportPath("./ManagerQml/Base");
#else
	engine->addImportPath("qrc:/ManagerQml/Base");
#endif // _TCDEBUG
	engine->addImportPath("qrc:/Qml/Base");

	// network access
	engine->setNetworkAccessManagerFactory(new MyQmlNetworkAccessManagerFactory);

#ifdef _TCDEBUG
	auto execPath = QStringLiteral("./ManagerQml/main.qml");
	if (!QFile::exists(execPath))
		return 0;
    engine->load(QUrl(execPath));
#else
	auto execPath = QStringLiteral("qrc:/ManagerQml/main.qml");
	engine->load(QUrl(execPath));
#endif // _TCDEBUG

    return app.exec();
}